package ru.tennisworld.match.services.impl;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import ru.tennisworld.match.data.enums.ValidationErrorEnum;
import ru.tennisworld.match.entities.Match;
import ru.tennisworld.match.exceptions.MatchValidationException;
import ru.tennisworld.match.services.ValidationService;
import ru.tennisworld.match.utils.ValidationResult;

import java.util.List;
import java.util.Objects;

@Service("validationService")
public class ValidationServiceImpl implements ValidationService {

    private static final Logger LOG = LoggerFactory.getLogger(ValidationServiceImpl.class);

    @Override
    public void validateMatch(Match match) {
        ValidationResult validationResult = new ValidationResult();
        validationResult.mergeValidation(validateMatchInfo(match));
        if (validationResult.isValidationError()) {
            throw new MatchValidationException("Ошибка валидации матча",  validationResult);
        }
    }

    private ValidationResult validateMatchInfo(Match match) {
        ValidationResult validationResult = new ValidationResult();
        if (match.getPlayersIds() == null || match.getPlayersIds().isEmpty()) {
            validationResult.addError(ValidationErrorEnum.MATCH_PLAYERS_IDS_NULL);
        } else {
            List<String> distinctPlayersIds = match.getPlayersIds().stream().distinct().toList();
            if (!Objects.equals(distinctPlayersIds, match.getPlayersIds())) {
                validationResult.addError(ValidationErrorEnum.MATCH_PLAYERS_IDS_NOT_UNIQUE);
            }
        }
        return validationResult;
    }

}
